package com.moxigua.iotbox.func;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.util.SPUtils;
import com.orhanobut.logger.Logger;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;

/**
 * 用于在后台运行接受MQTT服务器传来的消息，通过EventBus来与其他组件通信
 */
public class MqttService extends Service {
    private MqttClient mMqttClient;
    private String mServer;
    private String mUser;
    private String mPass;

    public MqttService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d("服务启动！！！！！！！！！！！");
        if (!TextUtils.isEmpty((String)SPUtils.get(Constants.SP_ENDPOINT, ""))) {
            mServer = Constants.PROTOCOL + SPUtils.get(Constants.SP_ENDPOINT, "") + Constants.PORT;
        }
        if (!TextUtils.isEmpty((String) SPUtils.get(Constants.SP_USER, ""))) {
            mUser = (String) SPUtils.get(Constants.SP_USER, "");
        }
        if (!TextUtils.isEmpty((String) SPUtils.get(Constants.SP_PASS, ""))) {
            mPass = (String) SPUtils.get(Constants.SP_PASS, "");
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(mServer) || TextUtils.isEmpty(mUser) || TextUtils.isEmpty(mPass)) {
                    EventBus.getDefault().post(new BaseEvent(Constants.TOPIC_ERR_NOCONFIG,new MqttMessage("连接失败，未设置账号密码".getBytes())));
                    return;
                }
                //当SP存在保存过的数据时直接启动并连接订阅
                try {
                    mMqttClient = MqttClientHepler.getInstance().connect(mServer, mUser, mPass);
                    MqttClientHepler.getInstance().subscribe();
                    Logger.d("连接注册成功");
                    EventBus.getDefault().post(new BaseEvent(Constants.TOPIC_NOR_CON_SUC,new MqttMessage("连接成功".getBytes())));
                } catch (MqttException e) {
                    EventBus.getDefault().post(new BaseEvent(Constants.TOPIC_ERR_CON_FAILD,new MqttMessage("连接失败，请检查设置".getBytes())));
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

}
